# -*- coding: utf-8 -*-
import random
import scrapy
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from zc_core.util.http_util import retry_request
from zc_core.spiders.base import BaseSpider
from huiemall.rules import *
from huiemall.items import HuiOrderItem, NoMatchOrderItem
from huiemall.utils.order_helper import OrderHelper
from zc_core.dao.order_pool_dao import OrderPoolDao
from zc_core.model.items import Box, OrderStatus


class OrderItemSpider(BaseSpider):
    name = 'order_item'
    # 常用链接
    order_list_url = 'http://www.huiemall.com/EpointMallHeFeiService/rest/system/getgonggaolist'
    order_detail_url = 'http://www.huiemall.com/EpointMallHeFeiService/rest/system/getgonggaodetail'
    search_url = 'http://www.huiemall.com/EpointMallHeFeiService/rest/product/search'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(OrderItemSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        self.order_helper = OrderHelper()

    def start_requests(self):
        # 处理订单列表
        order_list = OrderPoolDao().get_todo_list(self.batch_no, fields={'_id': 1, 'url': 1, 'orderTime': 1})
        if order_list:
            self.logger.info('目标: count=%s' % (len(order_list)))
            random.shuffle(order_list)
            for order in order_list:
                order_id = order.get('_id')
                order_time = order.get('orderTime')

                # 请求订单详情
                yield Request(
                    method='POST',
                    url=self.order_detail_url,
                    headers={
                        'Accept': 'application/json, text/javascript, */*; q=0.01',
                        'Content-Type': 'application/json',
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400',
                    },
                    body=json.dumps({
                        "type": "cj",
                        "gonggaoguid": order_id,
                        "gonggaotype": "undefined",
                        "referer": "http://www.huiemall.com/HeFei/noticedetail.html?type=cj&gonggaoguid={}&gonggaotype=undefined".format(
                            order_id)
                    }),
                    meta={
                        'reqType': 'order',
                        'orderId': order_id,
                        'orderTime': order_time,
                    },
                    callback=self.parse_order_item,
                    errback=self.error_back,
                    priority=100,
                )

    def parse_order_item(self, response):
        meta = response.meta
        order_id = meta.get('orderId')
        order_time = meta.get('orderTime')
        # 处理订单列表
        item_list = parse_order_item(response)
        if item_list:
            to_save_list = list()
            self.logger.info('数量: order=%s, cnt=%s' % (order_id, len(item_list)))
            for item in item_list:
                if item:
                    spu_id = item.get('spuId', '')
                    sp_name = item.get('supplierName')
                    sku_name = item.pop('skuName', '')
                    sp_id = self.order_helper.find_sp_id(sp_name)
                    if not spu_id and sku_name:
                        spu_id = self.order_helper.find_spu_id(sku_name)
                    else:
                        self.logger.debug('链接: %s' % spu_id)
                    if spu_id and sp_id:
                        # 留存商品源编号
                        item['spuId'] = spu_id
                        real_sku_id = build_sku_id(spu_id, sp_id)
                        item['skuId'] = real_sku_id
                        item['supplierId'] = sp_id
                        order_item = HuiOrderItem()
                        order_item.update(item)
                        self.logger.info('明细: id=%s' % (item.get('id')))
                        to_save_list.append(item)
                        # yield order_item
                    elif not spu_id and sp_id and sku_name:
                        # 发起商品池补充请求
                        yield Request(
                            method='POST',
                            url=self.search_url,
                            headers={
                                'Accept': 'application/json, text/javascript, */*; q=0.01',
                                'Content-Type': 'application/json',
                            },
                            body=json.dumps({
                                "productname": sku_name,
                                "brandname": "",
                                "cid": "",
                                "price": "",
                                "avgprice": "",
                                "sort": "salesvolume_desc",
                                "jnhb": "",
                                "page": "1",
                                "size": 12,
                                "isdingdian": "",
                                "platformurl": "http://www.huiemall.com/HeFei/goodssearch.html?productname={}".format(
                                    sku_name),
                                "referer": "http://www.huiemall.com/HeFei/goodssearch.html?productname={}".format(
                                    sku_name)
                            }),
                            meta={
                                'reqType': 'spu',
                                'batchNo': self.batch_no,
                                'orderId': order_id,
                                'supplierId': sp_id,
                                'supplierName': sp_name,
                                'skuName': sku_name,
                                'orderDict': item,
                            },
                            callback=self.parse_search_item,
                            errback=self.error_back,
                            priority=200,
                        )
                        self.logger.info('发起补充<order=%s, kw=%s>' % (order_id, sku_name))
                    else:
                        # 留存商品源编号
                        item['spuId'] = spu_id
                        item['supplierId'] = sp_id
                        item['skuName'] = sku_name
                        no_match_item = NoMatchOrderItem()
                        no_match_item.update(item)
                        self.logger.info('映射失败: %s' % (item.get('id')))
                        yield no_match_item
                else:
                    self.logger.error('订单商品异常: %s' % item)

            # 保存订单明细
            if to_save_list:
                yield Box('order_item', self.batch_no, to_save_list)
            # 标记订单已采
            if len(to_save_list) == len(item_list):
                order_status = OrderStatus()
                order_status['id'] = order_id
                order_status['orderTime'] = order_time
                order_status['batchNo'] = time_to_batch_no(order_time)
                order_status['workStatus'] = 1
                self.logger.info('完成: order=%s, cnt=%s' % (order_id, len(to_save_list)))
                yield order_status

    # 解析池商品
    def parse_search_item(self, response):
        meta = response.meta
        sp_id = meta.get('supplierId')
        sp_name = meta.get('supplierName')
        sku_name = meta.get('skuName')
        order_id = meta.get('orderId')
        order_dict = meta.get('orderDict')
        spu_list = parse_search_spu(response)
        if spu_list and sp_id:
            spu = spu_list[0]
            # 补充商品
            item_data = ItemData()
            item_data.update(spu)
            spu_id = spu.get('spuId')
            sku_id = build_sku_id(spu_id, sp_id)
            item_data['skuId'] = sku_id
            item_data['supplierId'] = sp_id
            item_data['supplierName'] = sp_name
            item_data['batchNo'] = self.batch_no
            self.logger.info('补充商品<sku=%s, spu=%s, kw=%s, order=%s>' % (sku_id, spu_id, sku_name, order_id))
            yield item_data

            # 补充同款
            self.logger.info('补充同款<order=%s, kw=%s, spus=%s>' % (order_id, sku_name, len(spu_list)))
            yield Box('spu', self.batch_no, spu_list)

            # 补充订单
            order_dict['spuId'] = spu_id
            real_sku_id = build_sku_id(spu_id, sp_id)
            order_dict['skuId'] = real_sku_id
            order_dict['supplierId'] = sp_id
            order_item = HuiOrderItem()
            order_item.update(order_dict)
            self.logger.info('补充订单[id=%s]' % (order_dict.get('id')))
            yield order_item
        else:
            self.logger.info('无补充商品<order=%s, kw=%s>' % (order_id, sku_name))
